<template>
    <div class="canvas-panel" ref="container">
        <v-stage ref="stageRef" :config="stageConfig" @mousedown="handleStageMouseDown">
            <v-layer>
                <v-rect :config="pageConfig" />

                <template v-for="element in elements" :key="element._id || element.id">
                    <v-text v-if="element.type === 'text'" :config="{ ...element, draggable: true }"
                        @dragend="handleDragEnd(element.id, $event)"
                        @mousedown="handleElementMouseDown(element.id, $event)"
                        @transformend="handleTransformEnd(element.id, $event)"
                        @dblclick="handleDblClick(element, $event)" @dbltap="handleDblClick(element, $event)" />
                    <v-image v-if="element.type === 'image'"
                        :config="{ ...element, image: imageElements[element.id], draggable: true }"
                        @dragend="handleDragEnd(element.id, $event)"
                        @mousedown="handleElementMouseDown(element.id, $event)"
                        @transformend="handleTransformEnd(element.id, $event)" />
                    <v-group v-if="element.type === 'table'" :config="{ ...element, draggable: true }"
                        @dragend="handleDragEnd(element.id, $event)"
                        @mousedown="handleElementMouseDown(element.id, $event)"
                        @transformend="handleTransformEnd(element.id, $event)">
                        <v-rect :config="{ width: element.width, height: 30, fill: '#EAEAEA' }" />
                        <template v-for="(header, index) in element.headers" :key="index">
                            <v-text :config="{
                                x: (element.columnWidths?.slice(0, index).reduce((a, b) => a + b, 0) || 0) + 5,
                                y: 8,
                                text: header,
                                fontSize: 14,
                                fill: 'black'
                            }" />
                        </template>
                        <v-rect
                            :config="{ width: element.width, height: element.height, stroke: '#333', strokeWidth: 1 }" />
                    </v-group>
                </template>
                <v-transformer ref="transformerRef" :rotate-enabled="true" />
            </v-layer>
        </v-stage>

        <textarea v-if="isEditing" ref="editingTextarea" v-model="editingText" :style="textareaStyle"
            @blur="handleTextareaBlur" @keydown.enter.prevent="handleTextareaBlur"></textarea>
    </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, watch, onMounted } from 'vue';
import { useTemplateStore, type TemplateElement } from '@/stores/templateStore';
import Konva from 'konva';
import { useTransformer } from '@/composables/useTransformer';
import { useDoubleClickEditing } from '@/composables/useDoubleClickEditing';

const store = useTemplateStore();
const elements = computed(() => store.elements);

// --- Refs and Configs ---
const container = ref<HTMLDivElement | null>(null);
const stageRef = ref<any>(null);
const transformerRef = ref<any>(null);

const stageConfig = reactive({ width: 800, height: 600 });
onMounted(() => {
    if (container.value) {
        stageConfig.width = container.value.offsetWidth;
        stageConfig.height = container.value.offsetHeight;
    }
});

// --- 【新增】页面背景矩形的计算属性 ---
const pageConfig = computed(() => {
    const stageWidth = stageConfig.width;
    const stageHeight = stageConfig.height;
    const { width: pageWidth, height: pageHeight } = store.pageSettings;

    return {
        // 计算 x, y 坐标使其在舞台上居中
        x: (stageWidth - pageWidth) / 2,
        y: (stageHeight - pageHeight) / 2,
        width: pageWidth,
        height: pageHeight,
        fill: 'white',
        shadowColor: 'black',
        shadowBlur: 10,
        shadowOpacity: 0.3,
        shadowOffsetX: 5,
        shadowOffsetY: 5,
    };
});


// --- 使用 Composables ---
useTransformer(stageRef, transformerRef);
const {
    isEditing,
    editingText,
    textareaStyle,
    editingTextarea,
    handleDblClick,
    handleTextareaBlur
} = useDoubleClickEditing(stageRef, transformerRef);

// --- 图片加载逻辑 ---
const imageElements = ref<Record<string, HTMLImageElement>>({});
watch(elements, (newElements) => {
    newElements.forEach(element => {
        if (element.type === 'image' && element.src && !imageElements.value[element.id]) {
            const img = new Image();
            img.crossOrigin = 'Anonymous';
            img.src = element.src;
            img.onload = () => { imageElements.value[element.id] = img; };
        }
    });
}, { deep: true, immediate: true });

// --- 事件处理器 ---
const handleDragEnd = (id: string, event: Konva.KonvaEventObject<DragEvent>) => {
    store.updateElement(id, { x: event.target.x(), y: event.target.y() });
};
const handleElementMouseDown = (id: string, event: Konva.KonvaEventObject<MouseEvent>) => {
    event.evt.preventDefault();
    store.selectElement(id);
};
const handleStageMouseDown = (event: Konva.KonvaEventObject<MouseEvent>) => {
    // 当点击白色页面背景时，也应取消选中元素
    if (event.target === event.target.getStage() || event.target.getAttr('fill') === 'white') {
        store.selectElement(null);
    }
};
const handleTransformEnd = (id: string, event: Konva.KonvaEventObject<Event>) => {
    const node = event.target;
    const elementInStore = store.elements.find(e => e.id === id);
    if (!elementInStore) return;
    const commonProps = { x: node.x(), y: node.y(), rotation: node.rotation() };
    let specificProps = {};
    if (elementInStore.type === 'text') {
        specificProps = {
            fontSize: (elementInStore.fontSize || 16) * node.scaleX(),
            width: node.width() * node.scaleX(),
            height: node.height() * node.scaleY(),
        };
    } else if (elementInStore.type === 'image') {
        specificProps = {
            width: node.width() * node.scaleX(),
            height: node.height() * node.scaleY(),
        };
    }
    store.updateElement(id, { ...commonProps, ...specificProps });
    node.scaleX(1);
    node.scaleY(1);
};
</script>

<style scoped>
/* 样式无变化 */
</style>